package com.suse.ecommerce.controller;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.suse.ecommerce.pojo.*;
import com.suse.ecommerce.serviceImp.RedisService;
import com.suse.ecommerce.service.SeckillService;
import com.suse.ecommerce.service.SeckillTimeService;
import com.suse.ecommerce.uilts.Msg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@Controller
public class SeckillController {

    private static final Logger logger= LoggerFactory.getLogger(SeckillController.class);
    @Autowired
    private SeckillService seckillService;

    @Autowired
    private SeckillTimeService seckillTimeService;

    @Autowired
    private RedisService redisService;

    //JVM缓存,存在一个问题，多态服务器JVM不同步，可以使用zookeeper保持同步
    private static ConcurrentHashMap<Long,Boolean> seckillConcuurentHashMap=new ConcurrentHashMap<>();


    @RequestMapping("/seckill/querySeckillProduct")
    @ResponseBody
    public Msg querySeckillProduct(@RequestParam("timeId")Integer timeId, HttpServletRequest request){
        List<Seckill> seckills = seckillService.querySekillByTime(timeId);
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        String date = simpleDateFormat.format(new Date());
        //使用日期+时间段作为key
        String redisTimeKey=date+"_time_" + timeId;
        String s = redisService.get(redisTimeKey);
        System.out.println("商品缓存....");
        if(s==null){
            //将每个商品的库存缓存到redis
            for (Seckill seckill:seckills){
                redisService.set(redisTimeKey,"yes",60*60*2);
                redisService.set(Contains.PRODUCTKEY+seckill.getId(),seckill.getStockCount()+"",60*60*2);
            }
        }
        return Msg.success("查询成功").add("seckills",seckills);
    }



    @RequestMapping("/seckill/querySeckillById")
    @ResponseBody
    public Msg querySeckillById(@RequestParam("seckillId") long seckillId){
        Seckill seckill = seckillService.querySeckillById(seckillId);
        return Msg.success("查询成功").add("seckill",seckill);
    }

    @RequestMapping("/auth/seckill/seckillConfrim")
    public Object seckillConfrim(@SessionAttribute("user")User user, @RequestParam("addressId") Long addressId,
                                 @RequestParam("seckillId") Long seckillId, HttpServletResponse response){
        System.out.println("/auth/seckill/seckillConfrim------------------------");
        if(seckillConcuurentHashMap.get(seckillId)!=null){
            return Msg.error("商品已售完");
        }
        redisService.increment("count");
        //减少redis的库存
        Long stock=redisService.decrement(Contains.PRODUCTKEY+seckillId);
        if(stock<0){
            //小于零后，必须加一
            seckillConcuurentHashMap.put(seckillId,true);
            redisService.increment(Contains.PRODUCTKEY+seckillId);
            return Msg.error("商品已售完");
        }
        try {
            SeckillOrder seckillOrder = seckillService.seckillConfrim(seckillId, user.getUserId(), addressId);
            //向支付宝发送请求
            //向支付宝发起支付请求
            String out_trade_no=seckillOrder.getId()+"";
            String subject="川理电商";
            String total_amount=seckillOrder.getSeckillPrice()/100+"";
            String body="";
            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(AlipayConfig.return_url);
            alipayRequest.setNotifyUrl(AlipayConfig.seckill_notify_url);
            alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                    + "\"total_amount\":\""+ total_amount +"\","
                    + "\"subject\":\""+ subject +"\","
                    + "\"body\":\""+ body +"\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            String	 result = alipayClient.pageExecute(alipayRequest).getBody();
            response.setContentType("text/html;charset=" + AlipayConfig.charset);
            response.getWriter().write(result);//直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();

        } catch (Exception e){
            e.printStackTrace();
            //如果发生异常  那么则需要把redis中的库存加1
            seckillConcuurentHashMap.remove(seckillId);
            redisService.increment("count");
            //清除JVM商品的标记
            seckillConcuurentHashMap.remove(seckillId);
            return  Msg.error("创建订单失败");
        }
        return null;
    }

    public String getRemortIP(HttpServletRequest request) {
        if (request.getHeader("x-forwarded-for") == null) {
            return request.getRemoteAddr();
        }
        return request.getHeader("x-forwarded-for");
    }

}
